﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using blackhouse.WebNemo.Business.Groups;
using blackhouse.WebNemo.Business;
using blackhouse.JavaScript.JQuery;
using System.Globalization;
using System.Text.RegularExpressions;

namespace blackhouse.WebNemo.Web.Controls {
    public partial class Records : System.Web.UI.UserControl {

        #region Fields

        private Factory factory = Factory.Instance();
        private int bindedToGroupId = -1;
        private IEnumerable<GroupRecord> bindedRecords;
        private CultureInfo editTranslate = CultureInfo.InvariantCulture;
        private int propGroupId;
        private IGroup group;

        #endregion

        #region Properties

        [Browsable(true)]
        [DefaultValue(0)]
        public int GroupId {
            get {
                return this.propGroupId;
            }
            set {
                if (this.propGroupId != value) {
                    this.propGroupId = value;
                    this.group = null;
                }
            }
        }

        public IGroup Group {
            get {
                if (this.group == null)
                    this.group = this.factory.GetGroup(this.propGroupId);
                return this.group;
            }
            set {
                this.group = value;
                this.propGroupId = (value == null) ? 0 : value.Id;
            }
        }

        [Browsable(true)]
        [DefaultValue(false)]
        public bool AllChecked { get; set; }

        [Browsable(true)]
        [DefaultValue(false)]
        public bool OneSelect { get; set; }

        public string GroupName {
            get {
                return (this.Group != null) ? this.Group.Name : String.Empty;
            }
        }

        #endregion

        #region Event Handlers

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            this.DataBind();
            NemoJsLibrary js = new NemoJsLibrary();
            js.IncludeJQueryUI();
            js.IncludeSorter();
            js.IncludeTableFilter();
            js.IncludeFile("nemo.grouplisting");

            if (GroupId > 0)
                this.ReceivePostback();

        }

        public override void DataBind() {
            base.DataBind();

            this.ReceivePostback();
            if (this.GroupId != this.bindedToGroupId) {
                this.SetInstance();
                this.PopulateControls();
                this.bindedToGroupId = this.GroupId;
            }
        }

        public void DataBind(IEnumerable<GroupRecord> records) {
            this.SetInstance(records);
            this.PopulateControls();
        }

        #endregion

        #region Methods

        private void ReceivePostback() {
            if (Request["action"] == "RemoveRecord") {
                int recordId = 0;
                if (Int32.TryParse(Request["recordId"], out recordId)) {
                    GroupRecord record = new GroupRecord(this.GroupId, recordId);
                    if (record.RecordId == recordId) {
                        record.Remove();
                        Response.Redirect(Request.RawUrl);
                        //NemoUrl url = NemoUrl.Get();
                        //url.GroupId = this.GroupId;
                        //url.View = NemoUrlView.RecordList;
                        //url.ShowMessage(NemoMessage.RecordRemoved);
                        //url.AddReturnUrl = false;
                        //Response.Redirect(url.GetUrl());
                    }
                }
            }
        }

        private void SetInstance(IEnumerable<GroupRecord> records) {
            if (records.Count() > 0) {
                IGroupRecord record = records.First();
                //this.GroupId = record.BelongsToGroupId;
                this.bindedToGroupId = record.BelongsToGroupId;
                //this.Group = factory.GetGroup(record.BelongsToGroupId);
                this.bindedRecords = records;
            }
        }

        private void SetInstance() {

            string translate = Request.QueryString["translate"];
            if (!String.IsNullOrEmpty(translate)) {
                try { this.editTranslate = CultureInfo.GetCultureInfo(translate); }
                catch { this.editTranslate = CultureInfo.InvariantCulture; }
            }
        }

        private void PopulateControls() {
            if (this.Group == null) {
                this.pnlRecords.Visible = false;
                this.pnlNoRecords.Visible = false;
                return;
            }
            else {
                this.groupId.Value = this.Group.Id.ToString();
                this.pnlRecords.Visible = true;
                this.pnlRecords.CssClass = "nemo-records dictionary-" + this.GroupId;

                IEnumerable<GroupRecord> records;

                if (this.bindedRecords != null)
                    records = this.bindedRecords;
                else {
                    CultureInfo ci = CultureInfo.CurrentCulture;
                    if (this.editTranslate != CultureInfo.InvariantCulture)
                        ci = this.editTranslate;

                    records = new GroupRecords(this.Group, ci);
                }

                if (records.Count() > 0) {
                    RecordsTable table = new RecordsTable();
                    table.EnableEditing = this.Group.Type == GroupType.Table;
                    if (this.editTranslate != CultureInfo.InvariantCulture)
                        table.TableForTranslating = this.editTranslate;
                    RecordExtension ext = RecordExtension.GetRecordExtension(Group);
                    if (ext != RecordExtension.NULL)
                        records = records.Where(ext.ShowOnRecordsList);

                    this.pnlRecords.Controls.Add(table);
                    table.Records = records.OrderByDescending(r => r.LastModifiedTime).ThenBy(r => r.Identyficator);
                    this.pnlNoRecords.Visible = false;
                }
                else {
                    this.pnlRecords.Visible = false;
                    NemoUrl url = NemoUrl.Get();
                    url.View = NemoUrlView.EditRecord;
                    url.GroupId = this.GroupId;
                    this.lnkToAddNew.NavigateUrl = url.GetUrl();
                }

                Page.Title = this.Group.Name + " - lista rekordów";

            }

        }

        internal static string GetSpecialParametersAsAppend() {
            Dictionary<string, string> spec = new Dictionary<string, string>();
            foreach (string qKey in HttpContext.Current.Request.QueryString.AllKeys) {
                switch (qKey) {
                    case "groupId":
                    case "mod":
                    case "modi":
                    case "message":
                        break;
                    default:
                        spec.Add(qKey, HttpContext.Current.Request.QueryString[qKey]);
                        break;
                }
            }
            if (spec.Count > 0)
                return string.Join("&", spec.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray());
            else
                return String.Empty;
        }

        //protected void rptRecords_ItemDataBound(object sender, RepeaterItemEventArgs e) {
        //    switch (e.Item.ItemType) {
        //        case ListItemType.AlternatingItem:
        //        case ListItemType.Item:

        //            IGroupRecord record = e.Item.DataItem as IGroupRecord;
        //            HyperLink lnkIdent = e.Item.FindControl("lnkIdent") as HyperLink;
        //            HyperLink lnkTime = e.Item.FindControl("lnkTime") as HyperLink;
        //            HyperLink lnkDisplay = e.Item.FindControl("lnkDisplay") as HyperLink;
        //            HyperLink lnkEdit = e.Item.FindControl("lnkEdit") as HyperLink;
        //            Literal checkType = e.Item.FindControl("checkType") as Literal;
        //            if (record != null) {
        //                if (lnkIdent != null) {
        //                    lnkIdent.Text = record.Identyficator.RemoveHtml();
        //                    lnkIdent.ToolTip = record.Identyficator.RemoveHtml();
        //                }

        //                if (lnkTime != null) {
        //                    DateTime time = record.LastModifiedTime;
        //                    if (time == null) time = record.CreatedTime;

        //                    lnkTime.Text = this.FormatToMaxShortTime(time);
        //                    lnkTime.ToolTip = time.ToString("F");
        //                }
        //            }

        //            if (this.OneSelect && checkType != null)
        //                checkType.Text = "radio";

        //            if (lnkDisplay != null)
        //                lnkDisplay.NavigateUrl = NemoUrlUtils.GetUrlUtils().GetDisplayRecord(record.BelongsToGroupId, record.RecordId);

        //            if (lnkEdit != null) {
        //                if (group.Type == GroupType.Table)
        //                    lnkEdit.NavigateUrl = NemoUrlUtils.GetUrlUtils().GetEditRecord(record.BelongsToGroupId, record.RecordId);
        //                else
        //                    lnkEdit.Visible = false;
        //            }

        //            break;
        //    }
        //}

        private string FormatToMaxShortTime(DateTime time) {
            if (time.Date == DateTime.Now.Date)
                return time.ToString("t");
            if (time.Year != DateTime.Now.Year)
                return time.ToString("d");
            return time.ToString("m");
        }

        public static int[] GetGlobalSelectedItems() {
            string[] s = HttpContext.Current.Request["selected-record"].Split(',');
            List<int> ai = new List<int>(s.Length);
            foreach (string si in s) {
                int i;
                if (Int32.TryParse(si, out i))
                    ai.Add(i);
            }
            return ai.ToArray();
        }

        #endregion

    }
}